//
//  Utility.m
//  HandPay
//
//  Created by xy on 10-4-20.
//  Copyright 2010 HANDPAY. All rights reserved.
//

#import "Utility.h"
#import "HPClientEngine.h"
#import "DefineUtil.h"
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <zlib.h>
#import "CUtility.h"
#import "CategoryUtil.h"
#import "ZZTongDefine.h"


//数字
#define NUM @"0123456789"
//字母
#define ALPHA @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
//数字和字母
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@implementation Utility

static NSString* systemVersion = nil;

+(NSString *)TreatUrl:(const char *)url withUrlTpye:(URLStype *)urltype {
	*urltype=UNKNOW_URL;
	NSString * result=@"";
	NSString * string=[NSString stringWithUTF8String:url];
	NSArray * paths=[string pathComponents];
	if (paths!=nil) {
		BOOL is_Mark=NO;
		NSString * temps=nil;
		NSEnumerator * enumi=[paths objectEnumerator];
		while (temps=[enumi nextObject]) {
			if ([temps isEqualToString:@"file:"]==YES) {
				if (is_Mark==NO) {
					*urltype=FILE_URL;
					continue;
				}
			}else if ([temps isEqualToString:@"res:"]==YES) {
				if (is_Mark==NO) {
					*urltype=RES_URL;
					continue;
				}
			}
			else if ([temps isEqualToString:@"net:"]==YES) {
				if (is_Mark==NO) {
					*urltype=NET_URL;
					continue;
				}
			}
			else if([temps isEqualToString:@"memory:"]==YES){
				if (is_Mark==NO) {
					*urltype=MEMORY_URL;
					continue;
				}
			}
			else if ([temps isEqualToString:@"cache:"]==YES) {
				if (is_Mark==NO) {
					*urltype=CACHE_URL;
					continue;
				}
			}
			else if ([temps isEqualToString:@"tmp:"]==YES) {
				if (is_Mark==NO) {
					*urltype=TEMP_URL;
					continue;
				}
			}
			else if ([temps isEqualToString:@"/"]==YES) {
				continue;
			}
			result=[result stringByAppendingPathComponent:temps];
		}
	}
	return result;
}

+(UIImage*)GetImageByName:(NSString *)name withPath:(NSString *)path{
	if (!path) {
		path = @"res/images/";
	}
	NSString* imagePath = [path stringByAppendingString:name];
	imagePath = [[NSBundle mainBundle] pathForResource:imagePath ofType:@"png"];
    return [UIImage imageWithContentsOfFile:imagePath];
}

+(NSString *)getTelephonyPhone{
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = info.subscriberCellularProvider;
    [info release];
    NSString *telephony = [NSString stringWithFormat:@"%@%@",[carrier mobileCountryCode],[carrier mobileNetworkCode]];
    NSString *phone = nil;
    if ([telephony isEqualToString:@"46000"] || [telephony isEqualToString:@"46002"] || [telephony isEqualToString:@"46007"]) {
         //中国移动
        phone = @"10086";
    }
    else if ([telephony isEqualToString:@"46001"]) {
        //中国联通
        phone = @"10010";
    }
    else if ([telephony isEqualToString:@"46003"]) {
        //中国电信
        phone = @"10001";
    }
    return phone;    
}

/*********************************** 身份证验证开始 ****************************************/
/**
 * 身份证号码验证 1、号码的结构 公民身份号码是特征组合码，由十七位数字本体码和一位校验码组成。排列顺序从左至右依次为：六位数字地址码，
 * 八位数字出生日期码，三位数字顺序码和一位数字校验码。 2、地址码(前六位数）
 * 表示编码对象常住户口所在县(市、旗、区)的行政区划代码，按GB/T2260的规定执行。 3、出生日期码（第七位至十四位）
 * 表示编码对象出生的年、月、日，按GB/T7408的规定执行，年、月、日代码之间不用分隔符。 4、顺序码（第十五位至十七位）
 * 表示在同一地址码所标识的区域范围内，对同年、同月、同日出生的人编定的顺序号， 顺序码的奇数分配给男性，偶数分配给女性。 5、校验码（第十八位数）
 * （1）十七位数字本体码加权求和公式 S = Sum(Ai * Wi), i = 0, ... , 16 ，先对前17位数字的权求和
 * Ai:表示第i位置上的身份证号码数字值 Wi:表示第i位置上的加权因子 Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4
 * 2 （2）计算模 Y = mod(S, 11) （3）通过模得到对应的校验码 Y: 0 1 2 3 4 5 6 7 8 9 10 校验码: 1 0
 * X 9 8 7 6 5 4 3 2
 */

/**
 * 功能：身份证的有效验证
 *
 * @param IDStr
 *            身份证号
 * @return 有效：返回null 无效：返回String信息**/
+(NSString *)IDCardValidate:(NSString *)IDStr{
    if (!IDStr || [IDStr isEqualToString:@""]) {
        return @"身份证号码无效";
    }
    NSString * valCode = @"10x98765432";
    //const int Wi [] = {'7','9','10','5','8','4','2','1','6','3','7','9','10','5','8','4','2'};
    const int Wi [] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    
    NSString * Ai = @"";
    
    IDStr = [IDStr lowercaseString] ;
    
    //号码的长度15位或则18位
    if ([IDStr length] != 15 && [IDStr length] != 18) {
        return @"身份证号码长度应该为15位或者18位";
    }
    
    //除最后一位都为数字
    if ([IDStr length] == 18) {
        Ai = [IDStr substringToIndex:17];
    }else if([IDStr length] == 15){
        Ai = [NSString stringWithFormat:@"%@19%@",[IDStr substringToIndex:6],[IDStr substringFromIndex:6]];
    }
    if (![Utility isPureInt:Ai]) {
        return @"身份证15位号码都应为数字；18位号码除最后一位外，都应为数字";
    }
    
    //出生年月是否有效
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSDate * date = [formatter dateFromString:[Ai substringWithRange:NSMakeRange(6, 8)]];
    [formatter release];
    //日期返回结果为nil，进行正则校验
    if (!date) {
        NSString *regex = @"^((19\\d{2})|(20\\d{2}))([0-1]{1}[0-9]{1})([0-3]{1}[0-9]{1})$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        BOOL isMatch = [pred evaluateWithObject:[Ai substringWithRange:NSMakeRange(6, 8)]];
        if (!isMatch) {
            return @"身份证生日无效";
        }
    }
    
    NSString * strYear = [Ai substringWithRange:NSMakeRange(6, 4)];
    NSString * strMonth = [Ai substringWithRange:NSMakeRange(10, 2)];
    NSString * strDay = [Ai substringWithRange:NSMakeRange(12, 2)];
    
    NSDate * nowDate = [NSDate date];
    
    NSCalendar* calendar = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents* comps = [calendar components:unitFlags fromDate:nowDate];
    
    if ((([comps year] - [strYear intValue]) > 150) ||  [nowDate timeIntervalSinceDate:date] < 0) {
        return @"身份证生日不在有效范围";
    }
    if ([strMonth intValue] > 12 || [strMonth intValue] == 0) {
        return @"身份证月份无效";
    }
    if ([strDay intValue] > 31 || [strDay intValue] == 0) {
        return @"身份证日期无效";
    }
    
    //地区码是否有效
    NSDictionary * dic = [Utility GetAreaCode];
    if ([dic objectForKey:[Ai substringToIndex:2]] == nil) {
        return @"身份证地区编码错误";
    }
    
    //判断最后一位的值
    int TotalmulAiWi = 0;
    for (int i = 0; i < 17; i++) {
        NSRange  range = NSMakeRange(i, 1);
        TotalmulAiWi = TotalmulAiWi + [[Ai substringWithRange:range] intValue] * Wi[i];
    }
    int modValue = TotalmulAiWi % 11;
    Ai = [NSString stringWithFormat:@"%@%@", Ai,[valCode substringWithRange:NSMakeRange(modValue, 1)]];
    
    if ([IDStr length] == 18) {
        if (![Ai isEqualToString:IDStr]) {
            return @"身份证无效，不是合法的身份证";
        }
    }
    return nil;
    
}
/**
 * 功能：设置地区编码
 */
+(NSDictionary *) GetAreaCode{
    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:10];

    [dic setObject:@"北京" forKey:@"11"];
    [dic setObject:@"天津" forKey:@"12"];
    [dic setObject:@"河北" forKey:@"13"];
    [dic setObject:@"山西" forKey:@"14"];
    [dic setObject:@"内蒙古" forKey:@"15"];
    [dic setObject:@"辽宁" forKey:@"21"];
    [dic setObject:@"吉林" forKey:@"22"];
    [dic setObject:@"黑龙江" forKey:@"23"];
    [dic setObject:@"上海" forKey:@"31"];
    [dic setObject:@"江苏" forKey:@"32"];
    [dic setObject:@"浙江" forKey:@"33"];
    [dic setObject:@"安徽" forKey:@"34"];
    [dic setObject:@"福建" forKey:@"35"];
    [dic setObject:@"江西" forKey:@"36"];
    [dic setObject:@"山东" forKey:@"37"];
    [dic setObject:@"河南" forKey:@"41"];
    [dic setObject:@"湖北" forKey:@"42"];
    [dic setObject:@"湖南" forKey:@"43"];
    [dic setObject:@"广东" forKey:@"44"];
    [dic setObject:@"广西" forKey:@"45"];
    [dic setObject:@"海南" forKey:@"46"];
    [dic setObject:@"重庆" forKey:@"50"];
    [dic setObject:@"四川" forKey:@"51"];
    [dic setObject:@"贵州" forKey:@"52"];
    [dic setObject:@"云南" forKey:@"53"];
    [dic setObject:@"西藏" forKey:@"54"];
    [dic setObject:@"陕西" forKey:@"61"];
    [dic setObject:@"甘肃" forKey:@"62"];
    [dic setObject:@"青海" forKey:@"63"];
    [dic setObject:@"宁夏" forKey:@"64"];
    [dic setObject:@"新疆" forKey:@"65"];
    [dic setObject:@"台湾" forKey:@"71"];
    [dic setObject:@"香港" forKey:@"81"];
    [dic setObject:@"澳门" forKey:@"82"];
    [dic setObject:@"国外" forKey:@"91"];
    
    return dic;
}
+ (void)adjustFontSizeWithLable:(UILabel*)label size:(CGFloat)fontSize{
    if (!label) {
        return;
    }
    CGRect frame = label.frame;
    int oriH = frame.size.height;
    int oriW = frame.size.width;
    
    frame.size.height = 1000;
    label.frame = frame;
    [label sizeToFit];
    frame = label.frame;
    
    int h = frame.size.height;
    
    frame.size.width = oriW;
    frame.size.height = oriH;
    label.frame= frame;
    
    if (h > oriH) {
        
        
        CGFloat fontS = fontSize - 1;
        if (fontSize > 10) {
            label.font = [UIFont systemFontOfSize:fontS];
            [Utility adjustFontSizeWithLable:label size:fontS];
        }else{
            label.font = [UIFont systemFontOfSize:fontSize];
            
        }
    }
}
//判断银行卡号合法性
+ (BOOL)isLegalCard:(NSString *) cardNo length:(int)length{
    if (!cardNo || [cardNo isEqualToString:@""] || [cardNo intValue] == 0) {
        return NO;
    }
    if (![Utility checkChar:cardNo type:HPCharType_Number]) {
        return NO;
    }
    if (length < 0 && length > 1) {
        length = 0;
    }
    int len = [cardNo length];
    NSString * number = [cardNo substringToIndex:(len - length - 1)];
    int verify = [[cardNo substringFromIndex:(len - length -1)] intValue];
    int count = 0;
    BOOL bMulti = YES;
    for (int i = ([number length] - 1); i >= 0 ; i--) {
        if (bMulti) {
            int multi = [[cardNo substringWithRange:NSMakeRange(i, 1)] intValue] * 2;
            if (multi > 9) {
                multi = multi - 9;
            }
            count = count + multi;
        }else{
            count = count + [[cardNo substringWithRange:NSMakeRange(i, 1)] intValue];
        }
        bMulti = ! bMulti;
    }
    
    if ((count + verify) % 10 == 0) {
        return YES;
    }else{
        if (length == 1) {
            return false;
        }
        if(cardNo.length <= 1)
        {
            return false;
        }
        return [self isLegalCard:cardNo length:1];
    }
}
/**
 * 判断给定年是否为闰年
 */
+ (BOOL)isLeapYear:(int)year{
    if (year < 0) {
        return NO;
    }
    if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
        return YES;
    }else{
        return NO;
    }
}
+ (BOOL)checkChar:(NSString*)string type:(HPCharType)type{
    NSString* oriStr = ALPHANUM;
    switch (type) {
        case HPCharType_Alpha:
            oriStr = ALPHA;
            break;
        case HPCharType_Number:
            oriStr = NUM;
            break;
        default:
            break;
    }
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:oriStr] invertedSet];
    NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [string isEqualToString:filtered];
}

+ (NSString *)convertString:(NSString *)string toType:(HPCharType)type
{
    if (string.length == 0)
    {
        return @"";
    }
    NSString * oriStr = ALPHANUM;
    if (type == HPCharType_Alpha)
    {
        oriStr = ALPHA;
    }
    else if (type == HPCharType_Number)
    {
        oriStr = NUM;
    }
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:oriStr] invertedSet];
    return [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
}

+ (BOOL)isPureInt:(NSString *)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
}

+ (BOOL)isPureFloat:(NSString *)string
{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return [scan scanFloat:&val] && [scan isAtEnd];
}
//+(NSString*)getNowDateTest{
//    NSDate* now = [NSDate date];
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
//    NSString* nowStr = [formatter stringFromDate:now];
//    [formatter release];
//    return nowStr;
//}
+(NSString*)getNowDateTime{
    NSDate* now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString* nowStr = [formatter stringFromDate:now];
    [formatter release];
    return nowStr;
}

+(NSString*)getNowDate{
    NSDate* now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString* nowStr = [formatter stringFromDate:now];
    [formatter release];
    return nowStr;
}
//yyyyMMddHHmmss 转化为 yyyyMMdd HH:mm:ss
+(NSString*)getFormatDate:(NSString*)date format:(NSString*)format{
    if ([NSString isNilOrEmpty:format]) {
        return [Utility getFormatDate:date];
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    
    NSDate* temp = [formatter dateFromString:date]; // 字符串先转为时间
    [formatter setDateFormat:format];
    
    NSString* str = [formatter stringFromDate:temp];
    [formatter release];
    return str;
}

+(NSString*)getFormatDate:(NSString*)date{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmss"];
    
    NSDate* temp = [formatter dateFromString:date]; // 字符串先转为时间
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString* str = [formatter stringFromDate:temp];
    [formatter release];
    return str;
}
//+(NSString*)getFormatDate2:(NSString*)date{
//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    
//    NSDate* temp = [formatter dateFromString:date]; // 字符串先转为时间
//    [formatter setDateFormat:@"yyyyMMddHHmmss"];
//    
//    NSString* str = [formatter stringFromDate:temp];
//    [formatter release];
//    return str;
//}

+ (UIControl *) currentResponseView:(UIView *)view
{
    NSArray *allSubviews = [self allSubViews:view];
    for (UIView *v in allSubviews) {
        if ([v isFirstResponder]) {
            return (UIControl *)v;
        }
    }
    
    return nil;
}

+ (NSArray *) canBecomeFirstRespondersOrderedInView:(UIView *)view
{
    NSMutableArray *canBecomeFirstResponders = [NSMutableArray array];
    NSArray *allSubviews = [self allSubViews:view];
    for (UIView *v in allSubviews) {
        if ([v isKindOfClass:[UITextField class]] && !v.hidden && v.userInteractionEnabled) {
            UITextField *tf = (UITextField *)v;
            if (tf.enabled) {
                [canBecomeFirstResponders addObject:v];
            }
        }
        
        if ([v isKindOfClass:[UITextView class]] && !v.hidden && v.userInteractionEnabled) {
            UITextView *tv = (UITextView *)v;
            if (tv.editable) {
                [canBecomeFirstResponders addObject:v];
            }
        }
    }
    
    [canBecomeFirstResponders sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        UIView *v1 = (UIView *)obj1;
        UIView *v2 = (UIView *)obj2;
        
        CGPoint p1 = [v1 convertPoint:(CGPoint){0, 0} toView:view];
        CGPoint p2 = [v2 convertPoint:(CGPoint){0, 0} toView:view];
        
        if (p1.y < p2.y) {
            return NSOrderedAscending;
        }
        if (p1.y > p2.y) {
            return NSOrderedDescending;
        }
        
        if (p1.x < p2.x) {
            return NSOrderedAscending;
        }
        if (p1.x > p2.x) {
            return NSOrderedDescending;
        }
        
        return NSOrderedSame;
    }];
    
    return canBecomeFirstResponders.count == 0 ? nil : canBecomeFirstResponders;
}

+ (NSArray *) allSubViews:(UIView *)view
{
    if (view  && view.subviews && view.subviews != 0) {
        NSMutableArray *ar = [NSMutableArray array];
        for (UIView *v in view.subviews) {
            [ar addObject:v];
            NSArray *a = [self allSubViews:v];
            if (a && a.count != 0) {
                [ar addObjectsFromArray:a];
            }
        }
        return ar;
    }
    return nil;
}

+ (BOOL)treatLeft:(NSMutableString*)dest input:(NSString*)input{
    if ([input length] > 10) {
        return YES;
    }
    int count = 10 - [input length];
    for (int i = 0; i < count; i++) {
        [dest appendString:@"0"];
    }
    [dest appendFormat:@"%@", input];
    return YES;
}

+ (BOOL)treatRight:(NSMutableString*)dest input:(NSString*)input{
    if (!input || [input length] == 0) {
        [dest appendString:@"00"];
        return YES;
    }
    
    if ([input length] > 2) {
        return NO;
    }
    
    int count = 2 - [input length];
    [dest appendString:input];
    
    for (int i = 0; i < count; i++) {
        [dest appendString:@"0"];
    }
    return YES;
}


+(NSString*)formatAmount:(NSString*)str{
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSArray* array = [str componentsSeparatedByString:@"."];
    NSMutableString* result = [[NSMutableString alloc] initWithCapacity:12];
    BOOL isSuccess = NO;
    if ([array count] == 1) {
        int length = [str length];
        if (length > 12) {
            isSuccess = YES;
            [result appendString:[str substringFromIndex:(length - 12)]];
        }else if(length == 12){
            isSuccess = YES;
            [result appendString:str];
        }else if(length == 11){
            isSuccess = YES;
            [result appendFormat:@"0%@", str];
        }else{
            isSuccess = [Utility treatLeft:result input:str];
            isSuccess = isSuccess & [Utility treatRight:result input:nil];
        }
    }else if ([array count] == 2){
        isSuccess = [Utility treatLeft:result input:array[0]];
        isSuccess = isSuccess & [Utility treatRight:result input:array[1]];
    }else{
        [result release];
        return nil;
    }
    if (!isSuccess) {
        [result release];
        return nil;
    }
    return [result autorelease];
}

+(NSString*)leftPadding:(NSString*)src withTotalCount:(int)count withChar:(NSString*)str{
    NSMutableString* result = [[NSMutableString alloc] init];
    
    
    int length = [src length];
    for (int i = 0; i < count - length; i++) {
        [result appendString:str];
    }
    [result appendString:src];
    LOG(@"leftPadding:%@", result);
    return [result autorelease];
}

+ (NSString*)getFormatMoneyAndSymbol:(NSString*)str{
    double moneyDouble = [str doubleValue];
    moneyDouble = moneyDouble / 100;
    return [NSString stringWithFormat:@"￥%0.2f", moneyDouble];
}

+ (NSString*)getFormatMoneyNoSymbol:(NSString*)str{
    double moneyDouble = [str doubleValue];
    moneyDouble = moneyDouble / 100;
    return [NSString stringWithFormat:@"%0.2f", moneyDouble];
}

+ (NSString*)formatAmount2:(NSString *)str{
    if (str.length <= 3) {
        return str;
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
//    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    [formatter setPositiveFormat:@"###,##0.00;"];
    
    NSNumber* number = [formatter numberFromString:str];
    NSString *result = [formatter stringFromNumber:number];
    
    [formatter release];
    return result;
}
+ (BOOL)isLegalDate:(NSString*)date{
    if ([NSString isNilOrEmpty:date]) {
        return NO;
    }
    NSString* strYear = [date substringToIndex:4];
    NSString* strMonth = [date substringWithRange:NSMakeRange(4, 2)];
    NSString* strDay = [date substringWithRange:NSMakeRange(6, 2)];
    
    if ([strMonth isEqualToString:@"02"]) {
        if ([strDay compare:@"29"] == NSOrderedDescending) {
            return NO;
        }
        if (![Utility isLeapYear:strYear.intValue] && ([strDay compare:@"29"] == NSOrderedDescending)){
            return NO;
        }
    }else if([strMonth isEqualToString:@"04"] ||
             [strMonth isEqualToString:@"06"] ||
             [strMonth isEqualToString:@"09"] ||
             [strMonth isEqualToString:@"11"] ){
        if ([strDay isEqualToString:@"31"]) {
            return NO;
        }
        
    }
    return YES;
    
}
+(NSString*)getSystemVersion{
    if (!systemVersion) {
        systemVersion = [[UIDevice currentDevice].systemVersion retain];
    }

    return systemVersion;
}
+(NSString*)encryptCardID:(NSString *)cardID{
    if (cardID.length < 8) {
        return cardID;
    }
 
    NSInteger cardLength = [cardID length];
   
    NSString* str = [NSString stringWithFormat:@"%@********%@",[cardID substringToIndex:4],[cardID substringFromIndex:(cardLength - 4)]];
    
    if (!str) {
        return cardID;
    }
    return [Utility getFormatCardID:str];
}
+(NSString*)crc32:(NSData*)data{
    uLong crc = crc32(0L, Z_NULL, 0);
    crc = crc32(crc, [data bytes], [data length]);
    return [NSString stringWithFormat:@"%lu",crc];
}
+(NSString*)toHexString:(NSData*)data{
    if (!data) {
        return nil;
    }
    const unsigned char* src = [data bytes];
    
    int srclen = [data length];
    
    char* result = (char *)malloc(sizeof(char) * (2 * srclen + 1));
    memset(result, 0, 2 * srclen + 1);
    
    int le = hexDecode(src, srclen, result);
    if (le == 0) {
        if (result) {
            free(result);
        }
        return nil;
    }
    
    NSString* strResult = [NSString stringWithUTF8String:result];
    if (result) {
        free(result);
    }
    return strResult;
    
}
+(NSString*)getFormatCardID:(NSString*)cardID{

    if ([cardID length] < 5){
        return cardID;
    }
    
    NSMutableString* str = [[NSMutableString alloc] init];
    NSInteger cardLength = [cardID length];
    NSInteger count  = cardLength / 4;
    if (cardLength % 4 != 0) {
        count++;
    }
    
    NSRange range;
    for (int i = 0; i < count; i++) {
        NSInteger leftCount = [cardID length] - i* 4;
        range = NSMakeRange(i * 4, leftCount < 4 ? leftCount : 4);
        if (i != 0) {
            [str appendString:@" "];
        }
        [str appendString:[cardID substringWithRange:range]];
    }
    
    return [str autorelease];
}
@end
